<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Feedback;
use app\common\model\UpgradeStandard;
use app\common\model\User as userModel;
use app\common\model\Address;
use app\common\model\NoticeList;
use app\common\model\UserGroup;
use app\common\model\UserMoneyLog;
use app\common\model\Withdrawal;
use app\common\model\Config;
use fast\Random;
use think\Validate;
use think\Db;

/**
 * 会员接口
 */
class User extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 个人中心
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1617845739",
    "data": {
    "id": 1,用户ID
    "avatar": "",头像
    "username": "admin",姓名
    "group_id": 2,会员级别1普通会员2一级会员3二级会员4三级会员
    "status_text": ""
    }
    })
     */
    public function index()
    {

        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id,avatar,username,group_id,mobile')->find();
        $this->success($user);
    }
    /**
     * 个人资料页面
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1617845843",
    "data": {
    "id": 1,
    "avatar": "",头像
    "username": "admin",姓名
    "status_text": ""
    }
    })
     */
    public function personal_html()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id,avatar,username')->find();
        $this->success($user_info);
    }
    /**
     * 个人资料保存
     * @ApiMethod   (POST)
     * @param string $username   姓名
     * @param string $avatar   头像
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 1,
    "msg": "修改成功",
    "time": "1617846027",
    "data": ""
    })
     */
    public function personal_edit()
    {
        $token = $this->request->post('token');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $data['username'] = $this->request->post('username');
        $data['avatar']  = $this->request->post('avatar');
        Db::startTrans();
        try {
            $res = userModel::where('id',$user_info['id'])->update($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('',__('修改成功'));
        }else{
            $this->error(__('修改失败'));
        }
    }
    /**
     * 收货地址列表
     * @param string $token TOKEN
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1600324552",
    "data": [{
    "id": 1,
    "userid": 1,
    "area": "河南省郑州市金水区",省市区
    "address": "明理路123号",详细地址
    "username": "张三",姓名
    "mobile": "13433333333",手机号
    "is_default": 1,是否默认0否1是
    "gender": 0,性别0先生1女士
    "createtime": null
    }, {
    "id": 2,
    "userid": 1,
    "area": "河南省郑州市金水区",
    "address": "明理路123号",
    "username": "张三",
    "mobile": "13433333333",
    "is_default": 0,
    "gender": 0,
    "createtime": null
    }]
    })
     */
    public function address_list()
    {
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id')->find();
        $list =Address::where('userid',$user_info['id'])->order('is_default desc,id desc')->select();
        foreach($list as &$value){
            $value['address'] = $value['province'].$value['city'].$value['area'].$value['address'];
        }
        $this->success($list);
    }
    /**
     * 收货地址添加
     * @ApiMethod   (POST)
     * @param string $username   姓名
     * @param string $mobile 手机号
     * @param string $province 省
     * @param string $city 市
     * @param string $area 区
     * @param string $address 详细地址
     * @param string $is_default 是否默认0否1是
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function insert_address()
    {
        $token = $this->request->post('token');
        $data['username'] = $this->request->post('username');
        $data['mobile'] = $this->request->post('mobile');
        $data['province'] = $this->request->post('province');
        $data['city'] = $this->request->post('city');
        $data['area'] = $this->request->post('area');
        $data['address'] = $this->request->post('address');
        $data['is_default'] = $this->request->post('is_default');
        $user = userModel::where('token',$token)->field('id')->find();
        if (!Validate::regex($data['mobile'], "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $this->shelis($data);
        Db::startTrans();
        try {
            $data['userid']=$user['id'];
            if($data['is_default'] == 1){
                Address::where('userid',$user['id'])->update(['is_default'=>0]);
            }
            $res = Address::create($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    /**
     * 收货地址编辑显示页面
     * @param string $id   收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "请求成功",
    "time": "1600325130",
    "data": {
    "id": 1,
    "userid": 1,
    "ptovince": "1",省
    "city": "2",市
    "area": "3",区
    "address": "明理路123号",详细地址
    "username": "张三",姓名
    "mobile": "13433333333",手机号
    "is_default": 1,是否默认0否1是
    "createtime": null
    }
    })
     */
    public function address_info()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user = userModel::where('token',$token)->field('id')->find();
        $info = Address::where(['userid'=>$user['id'],'id'=>$id])->find();
        if(empty($info)){
            $this->error('数据异常');
        }
        $this->success($info);

    }
    /**
     * 收货地址修改提交
     * @ApiMethod   (POST)
     * @param string $username   姓名
     * @param string $mobile 手机号
     * @param string $province 省
     * @param string $city 市
     * @param string $area 区
     * @param string $address 详细地址
     * @param string $is_default 是否默认0否1是
     * @param string $id 收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function edit_address()
    {
        $data['username'] = $this->request->post('username');
        $data['mobile'] = $this->request->post('mobile');
        $data['province'] = $this->request->post('province');
        $data['city'] = $this->request->post('city');
        $data['area'] = $this->request->post('area');
        $data['address'] = $this->request->post('address');
        $data['is_default'] = $this->request->post('is_default');
        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user = userModel::where('token',$token)->field('id')->find();
        if (!Validate::regex($data['mobile'], "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        $this->shelis($data);
        Db::startTrans();
        try {
            if($data['is_default'] == 1){
                Address::where('userid',$user['id'])->update(['is_default'=>0]);
            }
            $res = Address::where('id',$id)->update($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    /**
     * 收货地址删除
     * @ApiMethod   (POST)
     * @param string $id 收货地址ID
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 200,
    "msg": "申请提交成功",
    "data": ""
    })
     */
    public function delete_address()
    {

        $token = $this->request->post('token');
        $id = $this->request->post('id');
        $user = userModel::where('token',$token)->field('id')->find();
        $info = Address::where(['id'=>$id,'userid'=>$user['id']])->find();
        if($info){
            Db::startTrans();
            try {
                if($info['is_default'] == 1){
                    $also_info =  Address::where('id','<>',$id)->where('userid',$user['id'])->order('id asc')->find();
                    if($also_info){
                        Address::where('id','<>',$id)->where('id',$also_info['id'])->update(['is_default'=>1]);
                    }
                }
                $res = Address::where('id',$id)->delete();
                Db::commit();
            } catch (Exception $e) {
                $this->error($e->getMessage());
                Db::rollback();
                return false;
            }
            if($res){
                $this->success('','删除成功');
            }else{
                $this->error('删除失败');
            }
        }
        $this->error('数据异常');
    }
    private function shelis($data){
        $rule = [
            'username'  => 'require',
            'mobile'  => 'require',
            'province'  => 'require',
            'city'  => 'require',
            'area'  => 'require',
            'address'  => 'require',
        ];
        $msg = [
            'username.require'  => '请填写联系人姓名',
            'mobile.require'  => '请填写手机号',
            'province.require'  => '请选择省',
            'city.require'  => '请选择市',
            'area.require'  => '请选择区',
            'address.require'  => '请填写详细地址',
        ];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($data);
        if (!$result) {
            $this->error($validate->getError());
        }
    }
    /**
     * 消息列表
     * @param string $token TOKEN
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618885074",
    "data": [
    {
    "id": 1,消息ID
    "title": "这是个测试标题",标题
    "content": "&nbsp; &nbsp; &nbsp; &nbsp; 这是个测试标题这是个测试标题这是个测试标题这....",内容
    "createtime": "2021-04-07",时间
    "read_status": 0是否已读0否1是
    }
    ]
    })
     */
    public function notice_list()
    {
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        $token = $this->request->get('token');
        $user_info = userModel::where('token',$token)->field('id,group_id')->find();
        $list =NoticeList::where('group_id',$user_info['group_id'])->whereOr('group_id',0)->order('createtime desc')->field('id,title,content,createtime')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d',$value['createtime']);
            $value['content'] = StringToText($value['content'],50);
            //是否已读
            $value['read_status'] = Db::name('already_notice')->where(['notice_id'=>$value['id'],'userid'=>$user_info['id']])->count();
        }
        $this->success($list);
    }
    /**
     * 消息详情
     * @param string $token TOKEN
     * @param int $id 消息ID
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618885074",
    "data": [
    {
    "id": 1,消息ID
    "title": "这是个测试标题",标题
    "content": "&nbsp; &nbsp; &nbsp; &nbsp; 这是个测试标题这是个测试标题这是个测试标题这....",内容
    "createtime": "2021-04-07",时间
    }
    ]
    })
     */
    public function notice_detail()
    {
        $token = $this->request->get('token');
        $id = $this->request->get('id');
        $user_info = userModel::where('token',$token)->field('id,group_id')->find();
        $info =NoticeList::where('id',$id)->find();
        if($info){
            $info['createtime'] = date('Y-m-d',$info['createtime']);
            $info['content'] = get_img_thumb_url($info['content'],$this->domain);
            $read_status = Db::name('already_notice')->where(['notice_id'=>$info['id'],'userid'=>$user_info['id']])->count();
            if($read_status == 0){
                $data = [
                    'userid'=>$user_info['id'],
                    'notice_id'=>$info['id'],
                    'createtime'=>time(),
                ];
                Db::startTrans();
                try {
                    $res = Db::name('already_notice')->insert($data);
                    Db::commit();
                } catch (Exception $e) {
                    $this->error($e->getMessage());
                    Db::rollback();
                    return false;
                }
            }
            $this->success($info);
        }
        $this->error('暂无数据');
    }
    /**
     * 收益记录
     * @param varchar $token Token
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618972998",
    "data": [
    {
    "money": "200.00",金额
    "type": 2,类型1=直推奖,2=间推奖,3=级差奖
    "username": "用户1111",用户名
    "avatar": "/assets/img/avatar.png",头像
    "price": "100.00",订单金额
    "createtime": "2021-04-21 10:43",时间
    "status_string": "间推奖"
    },
    {
    "money": "100.00",
    "type": 1,
    "username": "用户1111",
    "avatar": "/assets/img/avatar.png",
    "price": "100.00",
    "createtime": "2021-04-21 10:43",
    "status_string": "直推奖"
    },
    {
    "money": "300.00",
    "type": 3,
    "username": "用户1111",
    "avatar": "/assets/img/avatar.png",
    "price": "100.00",
    "createtime": "2021-04-21 10:43",
    "status_string": "级差奖"
    }
    ]
    })
     */
    public function money_log()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        $list = UserMoneyLog::alias('m')->join('order o','o.id = m.order_id')->join('user u','u.id = o.userid')->where('m.userid',$user['id'])->where('m.type','in','1,2,3')->field('m.money,m.type,u.username,u.avatar,o.price,m.createtime')->order('m.createtime desc')->limit($page,$pagesize)->select();
        $status = [1=>'直推奖',2=>'间推奖',3=>'级差奖'];
        foreach($list as &$value){
            $value['avatar'] = $this->domain.$value['avatar'];
            $value['status_string'] = $status[$value['type']];
            $value['createtime'] = date('Y-m-d H:i');
        }
        $this->success($list);
    }
    /**
     * 提现记录
     * @param varchar $token Token
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1618973308",
    "data": [
    {
    "money": "100.00",提现金额
    "status": 2,状态:0=未审核 ,1=审核成功,2=审核失败
    "createtime": "2021-04-21 10:48",时间
    "reason": "545",驳回原因
    "type_text": "",
    "status_text": "Status 2"
    },
    {
    "money": "0.01",
    "status": 2,
    "createtime": "2021-04-21 10:48",
    "reason": "111",
    "type_text": "",
    "status_text": "Status 2"
    },
    {
    "money": "0.01",
    "status": 2,
    "createtime": "2021-04-21 10:48",
    "reason": "323",
    "type_text": "",
    "status_text": "Status 2"
    }
    ]
    })
     */
    public function withdrawal_log()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        $list = Withdrawal::where('userid',$user['id'])->field('money,status,createtime,reason')->order('createtime desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d H:i');
        }
        $this->success($list);
    }
    /**
     * 意见反馈提交
     * @ApiMethod   (POST)
     * @param string $content   反馈内容
     * @param string $images 截图，逗号隔开
     * @param string $token      用户token
     * @ApiReturn   ({
    "code": 1,
    "msg": "提交成功",
    "time": "1619081213",
    "data": ""
    })
     */
    public function feedback_sibmit()
    {
        $token = $this->request->post('token');
        $data['content'] = $this->request->post('content');
        $data['images'] = $this->request->post('images');
        $user = userModel::where('token',$token)->field('id')->find();
        if (!$data['content']) {
            $this->error('请填写反馈内容');
        }
        Db::startTrans();
        try {
            $data['userid']=$user['id'];
            $res = Feedback::create($data);
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res){
            $this->success('','提交成功');
        }else{
            $this->error('提交失败');
        }
    }
    /**
     * 我的影响力
     * @param varchar $token Token
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620437136",
    "data": {
    "total_influence": 3,总影响力
    "direct_push_num": 2,直推人数
    "jiantui_num": 1间推人数
    }
    })
     */
    public function my_influence()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id')->find();
        //总影响力
        $total_influence = userModel::where('find_in_set(:id,path)',['id'=>$user['id']])->count();
        //直推人数
        $direct_push_num = userModel::where('parent_id',$user['id'])->count();
        //间推人数
        $jiantui_num = ($total_influence-$direct_push_num)<=0?0:$total_influence-$direct_push_num;
        $data = [
            'total_influence'=>$total_influence,
            'direct_push_num'=>$direct_push_num,
            'jiantui_num'=>$jiantui_num,
        ];
        $this->success($data);
    }
    /**
     * 我的影响力-直推列表
     * @param varchar $token Token
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620437955",
    "data": [
    {
    "id": 2,
    "avatar": "/assets/img/avatar.png",头像
    "username": "用户1111",昵称
    "createtime": "2021-05-08",时间
    "direct_push_num": 0,直推人数
    "status_text": ""
    },
    {
    "id": 3,
    "avatar": "/assets/img/avatar.png",
    "username": "用户1111",
    "createtime": "2021-05-08",
    "direct_push_num": 1,
    "status_text": ""
    }
    ]
    })
     */
    public function direct_push_list()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        $list = userModel::where('parent_id',$user['id'])->field('id,avatar,username,createtime')->order('createtime desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d');
            //下级直推人数
            $value['direct_push_num'] = userModel::where('parent_id',$value['id'])->count();
        }
        $this->success($list);
    }
    /**
     * 我的影响力-间推列表
     * @param varchar $token Token
     * @param int $page 页数，默认1
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620438225",
    "data": [
    {
    "id": 4,
    "avatar": "http://shop.jiangyunwangluo.com/uploads/20210507/9731427184262e89720e473492d69947.jpg",头像
    "username": "yyc",昵称
    "createtime": "2021-05-08",时间
    "direct_push_num": 0,直推人数
    "status_text": ""
    }
    ]
    })
     */
    public function indirect_list()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id')->find();
        $pagesize = 10;
        $page  = $this->request->get('page')==null?1:$this->request->get('page');
        $page = ($page-1)*$pagesize;
        //当前用户直推列表
        $direct_push_list = userModel::where('parent_id',$user['id'])->field('id')->select();
        $ids  = [];
        foreach($direct_push_list as &$value){
            $ids[] = $value['id'];
        }
        $list = userModel::where('find_in_set(:id,path)',['id'=>$user['id']])->where('id','not in',$ids)->field('id,avatar,username,createtime')->order('createtime desc')->limit($page,$pagesize)->select();
        foreach($list as &$value){
            $value['createtime'] = date('Y-m-d');
            //下级直推人数
            $value['direct_push_num'] = userModel::where('parent_id',$value['id'])->count();
        }
        $this->success($list);
    }
    /**
     * 我的钱包
     * @param varchar $token Token
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620609455",
    "data": {
    "money": "9.50",可提现金额
    "total_income": 9.5总收益
    }
    })
     */
    public function my_wallet()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id,money')->find();
        //总收益
        $total_income = UserMoneyLog::where('userid',$user['id'])->where('type','in','1,2,3')->sum('money');
        $data = [
            'money'=>$user['money'],
            'total_income'=>$total_income,
        ];
        $this->success($data);
    }
    /**
     * 会员介绍
     * @param varchar $token Token
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1620719060",
    "data": {
    "id": 1,
    "group_id": 4,1普通会员 2一级会员 3二级会员 4三级会员
    "group_name": 普通会员, 会员名称
    "content": "<p>&nbsp; &nbsp; 会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介<img src=\"http://shop.jiangyunwangluo.com/uploads/20210511/ac5035a5688e83508c3a6722ffa76956.jpg\" >绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍会员规则介绍<br></p>",
    "status_text": ""
    }
    })
     */
    public function member_intro()
    {
        $token = $this->request->get('token');
        $user = userModel::where('token',$token)->field('id,group_id')->find();
        $info = UpgradeStandard::where('id',4)->field('content')->find();
        $user['group_name'] = UserGroup::where('id',$user['group_id'])->value('name');
        $user['content'] = get_img_thumb_url($info['content'],$this->domain);
        $this->success($user);
    }
    /**
     * 提现申请提交
     * @ApiMethod   (POST)
     * @param string $token  TOKEN
     * @param string $money  提现金额
     * @param string $type  提现类型0=微信,1=支付宝
     * @param string $account  手机号
     * @ApiReturn   ({
    "code": 1,
    "msg": "提现申请成功",
    "time": "1620723887",
    "data": ""
    })
     */
    public function withdrawal_apply()
    {
        $token = $this->request->post('token');
        $money = $this->request->post('money');
        $type = $this->request->post('type');
        $account = $this->request->post('account');
        $user = userModel::where('token',$token)->field('id,money')->find();
        if($money <0.01){
            $this->error('请填写提现金额');
        }
        if($user['money'] <$money){
            $this->error('余额不足');
        }
        if(!$account){
            $this->error('请填写手机号');
        }
        if (!Validate::regex($account, "^1\d{10}$")) {
            $this->error('手机号格式不正确');
        }
        //手续费
        $withdrawal_rate = Config::where('name','withdrawal_rate')->value('value');
        if(empty($withdrawal_rate)){
            $withdrawal_rate = 0;
        }
        //到账金额
        $arrive_money = $money*(1-$withdrawal_rate/100);
        $data = [
            'userid'=>$user['id'],
            'money'=>$money,
            'tixian_money'=>$arrive_money,
            'type'=>$type,
            'account'=>$account,
        ];
        Db::startTrans();
        try {
            $res = Withdrawal::create($data);
            if($res){
                $data1 = [
                    'userid'=>$user['id'],
                    'money'=>$money,
                    'type'=>4,
                    'createtime'=>time(),
                ];
                $res1 = UserMoneyLog::create($data1);
                if($res1){
                    $res2 = userModel::where('id',$user['id'])->setDec('money',$money);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            $this->error($e->getMessage());
            Db::rollback();
            return false;
        }
        if($res && $res1 && $res2){
            $this->success('','提现申请成功');
        }else{
            $this->error('提现失败');
        }
    }
}
